import {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProCard, {StatisticCard} from '@ant-design/pro-card';
import {Button, Dropdown, Form, Input, Menu, message, Popconfirm, Select, Space, Table} from 'antd';
import ProTable, {ActionType} from '@ant-design/pro-table';
import {DownOutlined} from '@ant-design/icons';
import ProForm, {ProFormRadio} from '@ant-design/pro-form';
import {DetectOrder, getOrderLists, PutWriteOff} from "@/services/ant-design-pro/order";
import OrderDetailsModal from "@/pages/order/components/OrderDetailsModal";
import OrderRecordModal from "@/pages/order/components/OrderRecordModal";
import OrderRemarksModal from "@/pages/order/components/OrderRemarksModal";
import DistributionInfoModal from "@/pages/order/components/DistributionInfoModal"
import SendGoodsModal from "@/pages/order/components/SendGoodsModal";
import UserInfo from "@/pages/order/components/UserInfo";
import OrderEditModal from "@/pages/order/components/OrderEditModal";

const OrderList = () => {
    const [isShowOrderDetail, setIsShowOrderDetail] = useState(false)   // 订单详情模态框状态
    const [isShowOrderRecord, setIsShowOrderRecord] = useState(false)  // 订单记录模态框状态
    const [isShowOrderRemarks, setIsShowOrderRemarks] = useState(false)  // 订单备注模态框状态
    const [isShowDistributionInformation, setIsShowDistributionInformation] = useState(false)  // 订单配送信息模态框状态
    const [isShowSendGoods, setIsShowSendGoods] = useState(false)  // 订单发送货
    const [isShowEdit, setIsShowEdit] = useState(false)             // 编辑模态框
    const [search, setSearch] = useState([])   // 顶部搜索状态
    const [orderSearch, setOrderSearch] = useState([]) // 订单状态的搜索
    const [paymentSearch, setPaymentSearch] = useState([]) // 支付状态的搜索
    const [searchKey, setSearchKey] = useState({})  // 选择输入框的搜索·转换前置Key
    const [selectSearch, setSelectSearch] = useState({}) // 选择输入框的搜索
    const [orderDetailId, setOrderDetailId] = useState(null)    // 订单详情id
    const [orderRecordId, setOrderRecordId] = useState(null)    // 订单记录id
    const [orderRemarksId, setOrderRemarksId] = useState(null)   // 订单备注id
    const [sendGoodsId, setSendGoodsId] = useState(null)         // 发送货id
    const [editId, setEditId] = useState(null)  // 订单编辑id
    const [orderNumber, setOrderNumber] = useState(null)   // props传送配送信息订单号
    const [OrderData, setOrderData] = useState({})   // 获取订单数量的数据
    const actionRef = useRef<ActionType>();  // 搜索状态更新
    const {Option} = Select;   // 组件内部转换 标签
    const {Search} = Input;
    //  搜索前的下拉框按钮数据
    const selectBefore = (
        <Select
            defaultValue="全部"
            className="select-before"
            onChange={(values) => {
                setSelectSearch({...selectSearch, values})
                setSearchKey(values)
            }}
            >
            <Option value="">全部</Option>
            <Option value="order_number">订单号</Option>
            <Option value="user_id">UID</Option>
            <Option value="nickname">用户姓名</Option>
            <Option value="phone">用户电话</Option>
            <Option value="total_num">订单中商品件数</Option>
            <Option value="info">商品名称(模糊)</Option>
        </Select>
    );
    // 表格中 操作下拉 数据
    const menu = (id, status, delStatus) => {
        return (
            <Menu>
                {status === 'noPaid' ?
                    <div>
                        {delStatus === 1 ?
                            <Menu.Item>
                                <a
                                    onClick={() => {}}
                                >
                                    立即支付
                                </a>
                        </Menu.Item>
                        : null
                        }
                        <Menu.Item>
                        <a rel="noopener noreferrer"
                              onClick={() => {
                                  setIsShowOrderDetail(true)
                                  setOrderDetailId(id)
                              }}
                        >
                            订单详情
                        </a>
                        </Menu.Item>
                        <Menu.Item>
                            <a rel="noopener noreferrer"
                                onClick={() => {
                                    setIsShowOrderRecord(true)
                                    setOrderRecordId(id)
                                }}
                            >
                                订单记录
                            </a>
                        </Menu.Item>
                        {delStatus === 0 ?
                            <Menu.Item>
                                <Popconfirm
                                    title="确定要删除此订单吗？ 删除将无法找回"
                                    onConfirm={async () => {
                                        await DetectOrder(id)
                                        message.success('订单删除成功')
                                        actionRef.current?.reload()
                                    }}
                                    okText="确定"
                                    cancelText="取消"
                                >
                                <a href="#">删除订单</a>
                              </Popconfirm>
                        </Menu.Item>
                        : null
                        }
                    </div>
                :
                    <div>
                        <Menu.Item>
                            <a rel="noopener noreferrer"
                                onClick={() => {
                                    setIsShowOrderDetail(true)
                                    setOrderDetailId(id)
                                }}
                            >
                                订单详情
                            </a>
                        </Menu.Item>
                        <Menu.Item>
                            <a rel="noopener noreferrer"
                               onClick={() => {
                                    setOrderRecordId(id)
                                    setIsShowOrderRecord(true)
                               }}
                            >
                               订单记录
                            </a>
                        </Menu.Item>
                        <Menu.Item>
                            <a rel="noopener noreferrer"
                                onClick={() => {
                                    setIsShowOrderRemarks(true)
                                    setOrderRemarksId(id)
                                }}
                            >
                                订单备注
                            </a>
                        </Menu.Item>
                        { delStatus === 0 ?
                            <Menu.Item>
                                <Popconfirm
                                    title="确定要删除此订单吗？ 删除将无法找回"
                                    onConfirm={async () => {
                                      await DetectOrder(id)
                                      message.success('订单删除成功')
                                      actionRef.current?.reload()
                                    }}
                                    okText="确定"
                                    cancelText="取消"
                                >
                                    <a href="#">删除订单</a>
                                </Popconfirm>
                            </Menu.Item>
                        : null
                        }
                    </div>
                }
        </Menu>
        )
    };
    // 订单列表的表头数据
    // @ts-ignore
	// @ts-ignore
	const columns = [
    {
        title: '订单号',
        dataIndex: 'order_number',
        align: 'center',
        search: false,
        render: ((_, record) => {
            return (
                <div>
                    <span>{record.order_number}</span>
                    {
                        record.is_user_delete === 0 ?
                        <p style={{color: 'red',position:'relative',top:'13px'}}>用户以删除</p>
                    : null
                    }
                </div>
            )
        })
    },
    {
        title: '订单类型',
        dataIndex: 'type_text',
        align: 'center',
        search: false
    },
    {
        title: '用户信息',
        dataIndex: 'user_name',
        align: 'center',
        search: false,
        render: (_, record) => {
            return <UserInfo UID={record.user.id} nickname={record.user.nickname}/>
        }
    },
    {
        title: '商品信息',
        search: false,
        align: 'center',
        render: (_, record) => {
            return  record.orderCartInfo?.cart_info.map(item=>{
                return (
                    <div style={{fontSize:'10px', display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                        <img
                            style={{width:'40px',marginTop:'4px' }}
                            src={item.image_url}
                        />
                        <div>{item.info}</div>
                        <div>￥ {item.price} x { item.num}</div>
                    </div>
                )
            })
        }
    },
    {
        title: '实际支付',
        dataIndex: 'pay_price',
        search: false,
        align: 'center',
    },
    {
        title: '支付时间',
        dataIndex: 'pay_time',
        search: false,
        align: 'center',
    },
    {
        title: '支付状态',
        dataIndex: 'status_text',
        search: false,
        align: 'center',
    },
    {
        title: '操作',
        fixed: 'right',
        align: 'center',
        search: false,
        width: 150,
        valueType: 'option',
        render: (_, record) => {
            switch (record.status) {
                case 'noPaid' :
                    return (
                        <div style={{display: 'flex', justifyContent: 'space-around'}}>
                            <a
                                onClick={() => {
                                    setIsShowEdit(true)
                                    setEditId(record.id)
                                }}
                            >
                                编辑
                            </a>
                            <Dropdown overlay={menu(record.id, record.status, record.is_user_delete)}>
                                <a onClick={e => e.preventDefault()}>
                                    更多 <DownOutlined/>
                                </a>
                            </Dropdown>
                        </div>
                    )
                case 'noDelivered' :
                    return (
                        <div style={{display: 'flex', justifyContent: 'space-around'}}>
                            <a
                                onClick={() => {
                                    setIsShowSendGoods(true)
                                    setSendGoodsId(record.id)
                                }}
                            >
                                发送货
                            </a>
                            <Dropdown overlay={menu(record.id, record.status, record.is_user_delete)}>
                                <a onClick={e => e.preventDefault()}>
                                     更多 <DownOutlined/>
                                </a>
                            </Dropdown>
                        </div>
                    )
                case 'toBeReceived' :
                    return (
                        <div style={{display: 'flex', justifyContent: 'space-around'}}>
                            <a
                                onClick={() => {
                                    setIsShowDistributionInformation(true)
                                    setOrderNumber(record.order_number)
                                }}
                            >
                                配送信息
                            </a>
                            <Dropdown overlay={menu(record.id, record.status, record.is_user_delete)}>
                                <a onClick={e => e.preventDefault()}>
                                    更多 <DownOutlined/>
                                </a>
                            </Dropdown>
                        </div>
                    )
                case 'beEvaluated' :
                    return (
                        <div style={{display: 'flex', justifyContent: 'space-around'}}>
                            <Dropdown overlay={menu(record.id, record.status, record.is_user_delete)}>
                                <a onClick={e => e.preventDefault()}>
                                    更多 <DownOutlined/>
                                </a>
                            </Dropdown>
                        </div>
                    )
                case 'dealDone' :
                    return (
                        <div style={{display: 'flex', justifyContent: 'space-around'}}>
                            <Dropdown overlay={menu(record.id, record.status, record.is_user_delete)}>
                                <a onClick={e => e.preventDefault()}>
                                    更多 <DownOutlined/>
                                </a>
                            </Dropdown>
                        </div>
                    )
                case 'toBeWriteOff' :
                    return (
                        <div style={{display: 'flex', justifyContent: 'space-around'}}>
                            <Popconfirm
                                title="确定要核销此订单吗？"
                                onConfirm={async () => {
                                    await PutWriteOff(record.id)
                                    message.success('订单核销成功')
                                    actionRef.current?.reload()
                                }}
                                okText="确定"
                                cancelText="取消"
                            >
                                <a href="#">订单核销</a>
                            </Popconfirm>
                            <Dropdown overlay={menu(record.id, record.status, record.is_user_delete)}>
                                <a onClick={e => e.preventDefault()}>
                                    更多 <DownOutlined/>
                                </a>
                            </Dropdown>
                        </div>
                    )
                case 'writtenOff' :
                    return (
                        <div style={{display: 'flex', justifyContent: 'space-around'}}>
                            <Dropdown overlay={menu(record.id, record.status, record.is_user_delete)}>
                                <a onClick={e => e.preventDefault()}>
                                    更多 <DownOutlined/>
                                </a>
                            </Dropdown>
                        </div>
                    )
            }
        }
    },
    ]
    return (
    <PageContainer
        header={{title: '订单管理', breadcrumb: {},}}
        // 导航订单数据
        tabList={ [
            {
                tab: `全部订单 (${OrderData.order_all || ''})`,
                key: '1',
            },
            {
                tab: `普通订单 (${OrderData.ordinaryOrder || ''})`,
                key: '2',
            },
            {
                tab: `拼团订单(${OrderData.pinkOrder || ''})`,
                key: '3',
            },
            {
                tab: `秒杀订单 (${OrderData.seckillOrder || ''})`,
                key: '4',
            },
            {
                tab: `砍价订单( ${OrderData.bargainOrder || ''})`,
                key: '5',
            },
        ] }
        // 导航订单类型 搜索条件拼接
        onTabChange={(key) => {
            switch (key) {
                case '1':
                    setSearch({
                        ...search,
                        ...{type: undefined }
                    })
                break;
                case '2':
                    setSearch({
                        ...search,
                        ...{type: 'ordinaryOrder'}
                    })
                break;
                case '3':
                    setSearch({
                        ...search,
                        ...{type: 'pinkOrder'}
                })
                break;
                case '4':
                    setSearch({
                        ...search,
                        ...{type: 'seckillOrder'}
                    })
                break;
                case '5':
                    setSearch({
                        ...search,
                        ...{type: 'bargainOrder'}
                    })
                break;
            }
            actionRef.current.reload();  // 刷新表格
        }}
    >
        {/* 订单卡片数据 */}
        <ProCard style={{marginTop: 2,}} gutter={[16, 16]}>
            <StatisticCard
                bordered
                statistic={{
                    value: `${OrderData.order_quantity || ''}`,
                    description: '订单数量',
                    icon: (
                        <img
                            style={{display: 'block', width: 60, height: 60,}}
                            src="https://gw.alipayobjects.com/mdn/rms_7bc6d8/afts/img/A*pUkAQpefcx8AAAAAAAAAAABkARQnAQ"
                            alt="icon"
                        />
                    )
                }}
            />
            <StatisticCard
                bordered
                statistic={{
                    value: `${(OrderData.order_amount * 1).toFixed(2) || ''}`,
                    description: '订单金额',
                    icon: (
                        <img
                            style={{display: 'block', width: 60, height: 60,}}
                            src=" https://gw.alipayobjects.com/mdn/rms_7bc6d8/afts/img/A*dr_0RKvVzVwAAAAAAAAAAABkARQnAQ"
                            alt="icon"
                        />
                    )
                }}
            />
            <StatisticCard
                bordered
                statistic={{
                    value: `${OrderData.order_quantity_today || ''}`,
                    description: '今日订单数量',
                    icon: (
                        <img
                            style={{display: 'block', width: 60, height: 60,}}
                            src="https://gw.alipayobjects.com/mdn/rms_7bc6d8/afts/img/A*-jVKQJgA1UgAAAAAAAAAAABkARQnAQ"
                            alt="icon"
                        />
                    )
                }}
            />
            <StatisticCard
                bordered
                statistic={{
                    value: `${OrderData.order_amount_today || ''}`,
                    description: '今日支付金额',
                    icon: (
                        <img
                            style={{display: 'block', width: 60, height: 60,}}
                            src="https://gw.alipayobjects.com/mdn/rms_7bc6d8/afts/img/A*FPlYQoTNlBEAAAAAAAAAAABkARQnAQ"
                            alt="icon"
                        />
                    )
                }}
            />
        </ProCard>
        {/* 订单状态 与 支付条件  搜索条件拼接 */}
        <div style={{ background: 'white', marginTop: '20px', padding: '15px'}}>
            <Form
                onValuesChange={(changeValues) => {
                    // 订单状态 条件搜索
                    switch (changeValues.orderButton) {
                        case '1':
                            setOrderSearch({
                                ...orderSearch,
                                ...{status: undefined ,is_user_delete: undefined}
                            })
                        break;
                        case '2':
                            setOrderSearch({
                                ...orderSearch,
                                ...{status: 'noPaid',is_user_delete: '1'}
                            })
                        break;
                        case '3':
                            setOrderSearch({
                                ...orderSearch,
                                ...{status: 'noDelivered'}
                            })
                        break;
                        case '4':
                            setOrderSearch({
                                ...orderSearch,
                                ...{status: 'toBeReceived'}
                            })
                        break;
                        case '5':
                            setOrderSearch({
                                ...orderSearch,
                                ...{status: 'beEvaluated'}
                            })
                        break;
                        case '6':
                            setOrderSearch({
                                ...orderSearch,
                                ...{status: 'dealDone'}
                            })
                        break;
                        case '7':
                            setOrderSearch({
                                ...orderSearch,
                                ...{status: 'toBeWriteOff'}
                            })
                        break;
                        case '8':
                            setOrderSearch({
                                ...orderSearch,
                                ...{status: 'writtenOff'}
                            })
                        break;
                        case '9':
                            setOrderSearch({
                                ...orderSearch,
                                ...{is_user_delete: '0' , status: undefined}
                            })
                        break;
                        }

                        // 支付方式 条件搜索
                    switch (changeValues.paymentButton) {
                        case '1' :
                            setPaymentSearch({
                                ...paymentSearch,
                                ...{pay_type: undefined }
                            })
                        break;
                        case '2' :
                            setPaymentSearch({
                                ...paymentSearch,
                                ...{pay_type: 'wechat'}
                            })
                        break;
                        case '3' :
                            setPaymentSearch({
                                ...paymentSearch,
                                ...{pay_type: 'alipay'}
                        })
                        break;
                        case '4' :
                            setPaymentSearch({
                                ...paymentSearch,
                                ...{pay_type: 'balance'}
                            })
                        break;
                        case '5' :
                            setPaymentSearch({
                                ...paymentSearch,
                                ...{pay_type: 'offline'}
                            })
                        break;
                        }

                    // 刷新表格
                    actionRef.current?.reload();
                }}
            >
                <ProFormRadio.Group
                    key={1}
                    name="orderButton"
                    label="订单状态 :"
                    radioType="button"
                    initialValue="1"
                    options={[
                        {
                            label: `全部 ${OrderData.order_all || ''}`,
                            value: '1',
                        },
                        {
                            label: `未支付 ${OrderData.noPaid || ''} `,
                            value: '2',
                        },
                        {
                            label: `未发货  ${OrderData.noDelivered || ''}`,
                            value: '3',
                        },
                        {
                            label: `待收货 ${OrderData.toBeReceived || ''}`,
                            value: '4',
                        },
                        {
                            label: `待评价  ${OrderData.beEvaluated || ''}`,
                            value: '5',
                        },
                        {
                            label: `交易完成 ${OrderData.dealDone || ''}`,
                            value: '6',
                        },
                        {
                            label: `待核销  ${OrderData.toBeWriteOff || ''}`,
                            value: '7',
                        },
                        {
                            label: `已核销 ${OrderData.writtenOff || ''}`,
                            value: '8',
                        },
                        {
                            label: `已删除 ${OrderData.deleted || ''}`,
                            value: '9',
                        },
                    ]}
                />
                <ProFormRadio.Group
                    key={2}
                    name="paymentButton"
                    label="支付方式 :"
                    radioType="button"
                    initialValue="1"
                    options={[
                        {
                            label: '全部 ',
                            value: '1',
                        },
                        {
                            label: '微信支付',
                            value: '2',
                        },
                        {
                            label: '支付宝支付',
                            value: '3',
                        },
                        {
                            label: '余额支付',
                            value: '4',
                        },
                        {
                            label: '线下支付',
                            value: '5',
                        },
                    ]}
                />
                <span style={{position:'relative',top:'5px',marginRight:'10px'}}>搜索 :</span>
                <Search
                    style={{width: '400px'}}
                    addonBefore={selectBefore}
                    placeholder="请输入"
					enterButton
                    onSearch={(data) => {
                        let item = {}
                        item[searchKey] = data
                        setSelectSearch(item)
                        actionRef?.current?.reload()
                    }}
                />
            </Form>
            <ProTable
                columns={columns}
                search={false}
                scroll={{x: 1400}}
                actionRef={actionRef}
                rowSelection={{
                    selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                }}
                tableAlertRender={({selectedRowKeys,selectedRows,onCleanSelected}) => (
                    <Space size={24}>
                        <span>
                            已选 {selectedRowKeys.length} 项
							<Popconfirm
								title="特变提醒: 批量删除只能删除用户已删除的订单, 您确定要批量删除吗? "
								onConfirm={async () => {
									let arr = selectedRowKeys.toString()
									await DetectOrder(arr)
									message.success('批量删除成功')
									actionRef.current?.reload()
								}}
								okText="确定"
								cancelText="取消"
							>
                                <a href="#" style={{marginLeft:'20px'}} >批量删除</a>
                            </Popconfirm>
                        </span>
                    </Space>
                )}
                // dataSource={date}
                request={async (params = {}, sort, filter) => {
                    let { data, meta} = await getOrderLists({...params, ...sort, ...filter, ...search, ...orderSearch, ...paymentSearch, ...selectSearch})
                    setOrderData(meta.show)
                    return {
                        data,
                        success: true,
                        total: meta.pagination.total
                    };
                }}
                editable={{
                    type: 'multiple',
                }}
                rowKey="id"
                ation={{
                    pageSize: 10,
                }}
                dateFormatter="string"
                headerTitle=""
                toolBarRender={() => [
                    <Button style={{marginLeft: '8px'}}>
                        下载物流公司对照表
                    </Button>
                ]}
            />
        </div>

        {/* 自定义Modal组件 */}
        { isShowOrderDetail ?
            <OrderDetailsModal
                visible={isShowOrderDetail}
                setVisible={setIsShowOrderDetail}
                id={orderDetailId}
                key={12}
                show={false}
            />
        : null}
        { isShowOrderRecord ?
            <OrderRecordModal
                key={23}
                visible={isShowOrderRecord}
                setVisible={setIsShowOrderRecord}
                id={orderRecordId}
            />
        : null
        }
        { isShowOrderRemarks ?
            <OrderRemarksModal
                visible={isShowOrderRemarks}
                setVisible={setIsShowOrderRemarks}
                id={orderRemarksId}
                mack={() => {
                    actionRef.current?.reload();
                }}
            />
        : null
        }
        {isShowDistributionInformation ?
            <DistributionInfoModal
                visible={isShowDistributionInformation}
                setVisible={setIsShowDistributionInformation}
                orderNumber={orderNumber}
            />
        : null
        }
        {isShowSendGoods ?
            <SendGoodsModal
                visible={isShowSendGoods}
                setVisible={setIsShowSendGoods}
                id={sendGoodsId}
            />
        : null
        }

        {isShowEdit ?
            <OrderEditModal
                visible={isShowEdit}
                setVisible={setIsShowEdit}
                id={editId}
                refreshEdit={() => {
                    actionRef.current?.reload()
                }}
            />
        : null }
    </PageContainer>
    )
};

export default OrderList;
